package string;

//最长公共前缀
public class LongestCommonPrefix {
    //使用【两两比较】的方法
    public String code(String[] strs) {
        String ret = strs[0];
        for (int i = 1; i < strs.length; i++){
            ret = findCommon(strs[i], ret);
        }

        return ret;
    }

    public String findCommon(String s1, String s2){
        int i = 0;
        while (i < Math.min(s1.length(), s2.length()) && s1.charAt(i) == s2.charAt(i)){
            i++;
        }

        return s1.substring(0, i);
    }

    //使用统一比较的方法
    public String code2(String[] strs) {
        for (int i = 0; i < strs[0].length(); i++){
            char tmp = strs[0].charAt(i);

            for (int j = 1; j < strs.length; j++){
                if (i == strs[j].length() || tmp != strs[j].charAt(i)){
                    return strs[0].substring(0, i);
                }
            }
        }

        return strs[0];
    }
}